package com.douyu.data.common.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class NetUtil {
    public static String getNetFileContent(String urlPath) throws MalformedURLException {

        // 下载网络文件
        int byteread = 0;
        URL url = new URL(urlPath);
        String result = "";
        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                result +=  new String(buffer, 0, byteread, "utf-8");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getHtmlFromUrl(String urlPath){
        String result = "";
        try {
            URL url = new URL(urlPath);
            URLConnection URLconnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, "utf-8");
                BufferedReader buff = new BufferedReader(isr);
                String str;
                while ((str = buff.readLine()) != null) {
                    result += str;
                }
                buff.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
